const express = require('express')
const router = express.Router()
const svgCaptcha = require("svg-captcha")
const UserModel = require('../db/models')
const RoutesModel = require('../db/routes')
const returnJson = require('./code')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const fs = require("fs");

const { secret } = require('../config/key')



const isAdmin = (req, res, next) => {
  const token = req.headers.authorization.split(' ').pop()
  const { _id, username } = jwt.verify(token, secret)
  UserModel.findById(_id).then(doc=>{
    if(!doc)return res.json(returnJson(422, '用户错误'))
    if(username !== doc.username){
      return res.json(returnJson(422, '用户错误'))
    }else{
      if(doc.isAdmin === '0'){
        return res.json(returnJson(409, '没有权限'))
      }else if(doc.isAdmin === '1'){
        next()
      }
    }
  })
}
// const jwt = require('jwt')
/**
 * @api {Get} /captcha 获取验证码
 * @apiGroup 登录
 */
router.get('/captcha', (req, res) => {
    let captcha = svgCaptcha.create({
      ignoreChars: '0o1l',
      noise: 2,
      color: true
    });
    req.sessionStore.captcha = captcha.text.toLowerCase();
    console.log(req.sessionStore.captcha)
    /*res.type('svg');
    res.status(200).send(captcha.data);*/
    res.type('svg');
    res.send(captcha.data)
});


router.get('/video', (req, res) => {
  let path = './assets/videos/aaa.mp4'
  let stat = fs.statSync(path);
  let fileSize = stat.size;
  let range = req.headers.range;

  // fileSize 3332038

  if (range) {
    //有range头才使用206状态码

    let parts = range.replace(/bytes=/, "").split("-");
    // console.log(range)
    let start = parseInt(parts[0], 10);
    start = start>fileSize?0:start
    let len = parseInt((fileSize-1)/50+'')
    let end = parts[1] ? parseInt(parts[1], 10) : start + len;

    // end 在最后取值为 fileSize - 1
    end = end > fileSize-1 ? fileSize-1 : end;

    let chunksize = (end - start)+1;
    let file = fs.createReadStream(path, { start, end });
    let head = {
      'Content-Range': `bytes ${start}-${end}/${fileSize}`,
      'Accept-Ranges': 'bytes',
      'Content-Length': chunksize,
      'Content-Type': 'video/mp4',
    };
    res.writeHead(206, head);
    file.pipe(res);
  } else {
    let head = {
      'Content-Length': fileSize,
      'Content-Type': 'video/mp4',
    };
    res.writeHead(200, head);
    fs.createReadStream(path).pipe(res);
  }
});

router.post('/register', (req, res) => {
  const now = new Date()
  const userData = Object.assign(req.body,{created: now})
  UserModel.findOne({username:userData.username}).then(doc=>{
    if(!doc){
      bcrypt.hash(userData.password, 10).then(hash=>{
        userData.password=hash
        new UserModel(userData).save(()=>{
          res.json(returnJson(200, '注册成功！'))
        })
      })
    }else{
      res.json(returnJson(409,'该用户已存在'))
    }
  }).catch(err=>{
    res.json(returnJson(404, `errer${err}`))
  })
})


router.post('/login', function (req, res) {
  const userData = req.body
  if(userData.captcha!==req.sessionStore.captcha) {
    return res.json(returnJson(422, '验证码不正确'))
  }
  delete req.sessionStore.captcha
  UserModel.findOne({username:userData.username}).then(doc=>{
    if(doc){
      if (bcrypt.compareSync(userData.password, doc.password)) {
        const { _id, username } = doc
        let token = jwt.sign({ _id, username }, secret, { expiresIn:1440 })
        res.json(returnJson(200, '登录成功', {token}))
      }else{
        res.json(returnJson(422, '密码错误'))
      }
    }else{
      res.json(returnJson(422, '用户名不存在'))
    }
  }).catch(err=>{
    res.send(returnJson(404, `errer${err}`))
  })
})

router.get('/verify', isAdmin,async (req, res)=>{
  const list = await UserModel.find()
  res.send(list)
})


router.get('/getRoutes', async (req, res)=>{
  const list = await RoutesModel.find()
  new RoutesModel({
    name:'541'
  }).save()
  res.send(list)
})

router.get('/test', async (req, res)=>{
  res.json({list:200})
})


module.exports = router